/**
 * Project Name:sales-query-service
 * File Name:DistributeCacheLock.java
 * Package Name:com.vip.somp.sales.frontend.util
 * Date:2016年4月18日下午6:12:27
 * Copyright (c) 2016, vipshop.com All Rights Reserved.
 */

package com.github.xiaolyuh.lock;

import com.github.xiaolyuh.entity.CacheLockObject;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存使用的锁控制
 *
 * @author xuwanglong
 */
public class CacheLock {
    private static CacheLock lock = new CacheLock();
    private static ConcurrentHashMap<String, CacheLockObject> records = new ConcurrentHashMap<String, CacheLockObject>();

    private CacheLock() {}

    public static CacheLock getInstance() {
        return lock;
    }

    /**
     * 判断锁
     */
    public boolean isLocked(String key) {
        return records.containsKey(key);
    }

    /**
     * 加锁
     */
    public boolean tryLock(String key) {
        CacheLockObject curVal = new CacheLockObject(key);
        CacheLockObject preVal = records.putIfAbsent(key, curVal);
        if (null == preVal) {
            return true;
        }
        return !preVal.getKey().equals(curVal.getKey());
    }

    /**
     * 拿锁
     */
    public CacheLockObject getLock(String key) {
        return records.get(key);
    }

    /**
     * 解锁
     */
    public void unLock(String key) {
        records.remove(key);
    }

}
